package com.pizzastudio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
//import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.json.simple.JSONArray;
//import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
//import org.json.simple.parser.ParseException;

//import java.util.logging.Logger;

public class TranslateServlet extends HttpServlet {
	//private static final Logger log = Logger.getLogger(TranslateServlet.class.getName());
	
	private String server_url = "http://translate.google.com";
	private String req_url = "/translate_a/t";
	private String midEnc = "ja";
	private JSONParser parser = new JSONParser();
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/javascript; charset=UTF-8");
		String fromEnc = req.getParameter("fromEnc");
		if(fromEnc == null)
			fromEnc = "en";
		String toEnc = req.getParameter("toEnc");
		if(toEnc == null)
			toEnc = "ko";
		String firstResult = retriveInfoFromStr(retreiveInfoFromUrl(req.getParameter("sln"), fromEnc, midEnc));
//		System.out.println("firstResult : " + firstResult);
		String secondResult = retriveInfoFromStr(retreiveInfoFromUrl(firstResult, midEnc, toEnc));
//		System.out.println("secondResult : " + secondResult);
		resp.getWriter().print(secondResult);		
	}
	
	private String retriveInfoFromStr(String rsp){
		JSONArray root = null;
		StringBuilder sb = new StringBuilder();

		rsp = rsp.replace("<", " ").replace(">", " ").replace(":", " ");
		try {
			root = (JSONArray) parser.parse(rsp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// [[["テスト","test","Tesuto",""]],[["noun",["テスト","試験","試し","試練","考査"],[["テスト",["test"],,0.43009463],["試験",["test","exam","study","examination","quiz"],,0.18789443],["試し",["trial","test","experiment","attempt"],,0.0011708796],["試練",["test","trial","ordeal","probation"],,0.00043074254],["考査",["examination","test","consideration","quiz"],,1.5689797e-05]]],["verb",["試す","試みる"],[["試す",["try","test","attempt"],,0.00016606605],["試みる",["try","test"],,5.2554233e-06]]]],"en",,[["テスト",[5],0,0,584,0,1,0]],[["test",4,,,""],["test",5,[["テスト",584,0,0],["試験",320,0,0],["検定",48,0,0],["検査",46,0,0],["のテスト",0,0,0]],[[0,4]],"test"]],,,[["en"]],2]
		JSONArray firstArr = (JSONArray) root.get(0); //log.info("### firstArr.toString() is " + firstArr.toJSONString());
		Iterator<JSONArray> secondIr = firstArr.iterator();
		while(secondIr.hasNext()){
			sb.append(secondIr.next().get(0));
			
		}
//		System.out.println("### obj is " + sb.toString());
		return sb.toString().trim();
	}
	private String retreiveInfoFromUrl(String text , String stype, String ttype){
		
		StringBuilder textView = new StringBuilder();
		try {
			String path = server_url + req_url;
			String query = makeParam(text, stype, ttype);
//			System.out.println(path);
			URL url = new URL(path);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty("User-Agent", 
            	    "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17");
            connection.addRequestProperty("Accept-Charset", 
            	    "windows-949,utf-8;q=0.7,*;q=0.3");
            connection.addRequestProperty("Content-Length", 
            	    ""+query.length());
            connection.addRequestProperty("Accept-Language", 
            	    "ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4");
            connection.addRequestProperty("Host", 
            	    "translate.google.com");
            connection.addRequestProperty("Referer", 
            	    "http://translate.google.com/");
            connection.addRequestProperty("Accept", 
            	    "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            
            
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(query);
            writer.close();
            
            BufferedReader in = new BufferedReader(new InputStreamReader(
            		connection.getInputStream(), "utf-8"));
            
//            for(int i=0;;i++){
//            	System.out.print(connection.getHeaderFieldKey(i) + "=");
//            	System.out.println(connection.getHeaderField(i));
//            	if(connection.getHeaderField(i) == null) break;
//            }
//            
            
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
//            	System.out.println(inputLine);
            	textView.append(inputLine);
            }
            in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return textView.toString();
	}
	
	private String makeParam(String text, String stype, String ttype) {
		List<BasicNameValuePair> param = new ArrayList<BasicNameValuePair>(13);
		// '/translate_a/t?client=t&text=today&hl=en&sl=en&tl=ja&ie=UTF-8&oe=UTF-8&multires=1&prev=btn&ssel=0&tsel=0&uptl=ja&alttl=ko'
		param.add(new BasicNameValuePair("client","t"));
		param.add(new BasicNameValuePair("text",text));
		param.add(new BasicNameValuePair("hl",stype)); // 
		param.add(new BasicNameValuePair("sl",stype)); //
		param.add(new BasicNameValuePair("tl",ttype)); // 
		param.add(new BasicNameValuePair("ie","UTF-8"));
		param.add(new BasicNameValuePair("oe","UTF-8"));
		param.add(new BasicNameValuePair("multires","1"));
		param.add(new BasicNameValuePair("prev","btn"));
		param.add(new BasicNameValuePair("ssel","0"));
		param.add(new BasicNameValuePair("tsel","0"));
		param.add(new BasicNameValuePair("sc","1")); //
		//log.info(toQueryString(param, false));
		return toQueryString(param, false);
	}

	public static String toQueryString( List<BasicNameValuePair> params, boolean xml ) {
	    StringBuilder sb = new StringBuilder(128);
	    try {
	      String amp = xml ? "&amp;" : "&";
	      boolean first=true;
	      Iterator<BasicNameValuePair> names = params.iterator();
	      while( names.hasNext() ) {
	    	  BasicNameValuePair namevalue = names.next();
	    	
	        String key = namevalue.getName();
	        String val = namevalue.getValue();
	        sb.append( first? "":amp );
	        sb.append(key);
	        if( val != null ) {
	        	sb.append('=');
	            sb.append( URLEncoder.encode( val, "UTF-8" ) );
	        }
	        first=false;
	      }
	    }
	    catch (IOException e) {throw new RuntimeException(e);}  // can't happen
	    return sb.toString();
	  }
	
}
